define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
	function getTr(item) {
		return `<tr style="text-align: center; vertical-align: middle; ">
			<td>${item.products.id}</td>
			<td>${item.products.name}</td>
			<td>${item.price}</td>
			<td>${item.pronum}</td>
			<td>${item.total}</td>
		</tr>
		`;
	}

	const addAndEditTableColumns = [
		{
			field: 'id',
			title: '主键',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'name',
			title: '商品名称',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'price',
			title: '商品单价',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'nums',
			title: '数量',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'total',
			title: '总价',
			halign: 'center',
			valign: 'middle',
		},
	];

	const controller = {
		index() {
			Table.api.init({
				extend: {
					index_url: 'depot/back/index' + location.search,
					add_url: 'depot/back/add',
					edit_url: 'depot/back/edit',
					del_url: 'depot/back/del',
					table: 'depot_back',
				},
			});

			const table = $('#table');

			table.bootstrapTable({
				// 请求地址
				url: $.fn.bootstrapTable.defaults.extend.index_url,
				pk: 'id',
				sortName: 'id',
				fixedColumns: true,
				fixedRightNumber: 1,
				onLoadSuccess: function () {
					$('.btn-editone, .btn-edit').data('area', ['100%', '100%']);

					// 给添加按钮添加`data-area`属性
					$('.btn-add').data('area', ['100%', '100%']);
				},
				// 渲染表格数据
				columns: [
					{
						checkbox: true,
						formatter: function (value, row, index) {
							if (row.status == 2) {
								return { disabled: true };
							} else if (row.status == 3) {
								return { disabled: true };
							}
						},
					},
					{ field: 'id', title: __('Id') },
					{ field: 'code', title: __('Code'), operate: 'LIKE' },
					{ field: 'ordercode', title: __('Ordercode'), operate: 'LIKE' },
					{ field: 'business.nickname', title: __('Busid') },
					{ field: 'contact', title: __('Contact'), operate: 'LIKE' },
					{ field: 'phone', title: __('Phone'), operate: 'LIKE' },
					{ field: 'amount', title: __('Amount'), operate: 'BETWEEN' },
					{
						field: 'createtime',
						title: __('Createtime'),
						operate: 'RANGE',
						addclass: 'datetimerange',
						autocomplete: false,
						formatter: Table.api.formatter.datetime,
					},
					{
						field: 'status',
						title: __('Status'),
						searchList: {
							0: __('未审核'),
							1: __('已审核，未收货'),
							2: __('已收货，未入库'),
							3: __('已入库'),
							'-1': __('审核不通过'),
						},
						formatter: Table.api.formatter.status,
					},

					{
						field: 'operate',
						title: __('Operate'),
						table: table,
						events: Table.api.events.operate,
						formatter: Table.api.formatter.operate,
						buttons: [
							{
								name: 'detail',
								title: '详情',
								classname: 'btn btn-xs btn-success btn-dialog',
								extend: 'data-toggle="tooltip" data-container="body"',
								url: 'depot/back/detail',
								icon: 'fa fa-eye',
							},
							{
								name: 'process',
								title: '通过审核',
								classname: 'btn btn-xs btn-success btn-ajax',
								icon: 'fa fa-check',
								confirm: '确认通过审核吗？',
								url: 'depot/back/process',
								extend: 'data-toggle="tooltip" data-container="body"',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									if (row.status == 0) {
										return true;
									}
									return false;
								},
							},
							{
								name: 'receipt',
								title: '确认收货',
								classname: 'btn btn-xs btn-success btn-ajax',
								icon: 'fa fa-leaf',
								confirm: '确认收货吗？',
								extend: 'data-toggle="tooltip" data-container="body"',
								url: 'depot/back/receipt',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									return row.status == 1 ? true : false;
								},
							},
							{
								name: 'storage',
								title: '确认入库',
								classname: 'btn btn-xs btn-success btn-ajax',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-leaf',
								confirm: '确认入库吗？',
								url: 'depot/back/storage',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									return row.status == 2 ? true : false;
								},
							},
							{
								name: 'fail',
								title: '未通过审核',
								classname: 'btn btn-xs btn-info btn-dialog',
								icon: 'fa fa-close',
								extend: 'data-toggle="tooltip" data-container="body"',
								confirm: '确认未通过审核吗？',
								url: 'depot/back/fail',
								visible: function (row) {
									if (row.status == 0) {
										return true;
									}
									return false;
								},
							},
							{
								name: 'cancel',
								title: '撤销审核',
								classname: 'btn btn-xs btn-danger btn-ajax',
								icon: 'fa fa-reply',
								url: 'depot/back/cancel',
								confirm: '确认要撤回审核吗？',
								extend: 'data-toggle="tooltip" data-container="body"',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									if (row.status == 1) {
										return true;
									}

									return false;
								},
							},
							{
								name: 'edit',
								title: '编辑',
								classname: 'btn btn-xs btn-success btn-editone',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-pencil',
								url: 'depot/storage/edit',
								visible: function (row) {
									if (row.status == 2 || row.status == 3) {
										return false;
									}

									return true;
								},
							},
							{
								name: 'del',
								title: '删除',
								classname: 'btn btn-xs btn-danger btn-delone',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-trash',
								visible: function (row) {
									if (row.status == 2 || row.status == 3) {
										return false;
									}

									return true;
								},
							},
						],
					},
				],
			});

			Table.api.bindevent(table);
		},
		add() {
			$('#table').bootstrapTable({
				columns: addAndEditTableColumns,
			});

			$('#table').hide();

			let timer;
			$('#c-ordercode').on('change', function () {
				const code = $(this).val();
				if (timer) clearTimeout(timer);
				timer = setTimeout(() => getInfo(code), 300);
			});

			function getInfo(code) {
				if (!code) return;
				$.ajax({
					type: 'post',
					url: 'depot/back/orderinfo',
					data: {
						code,
					},
					dataType: 'json',
					success: function (res) {
						if (res.code === 0) {
							Toastr.error(res.msg);

							return false;
						}

						$('#table').show();

						$('#table tbody').empty();

						let tr = '';

						for (let i = 0; i < res.data.productList.length; i++) {
							tr += getTr(res.data.productList[i]);
						}

						$('#table tbody').html(tr);

						// 收货地址
						let option = '';

						for (let item of res.data.addressList) {
							option += `<option value="${item.id}" ${
								item.id == res.data.businessaddrid ? 'selected="selected"' : ''
							}>联系人：${item.consignee} 联系方式：${item.mobile} 地址：${item.region_text} ${
								item.address
							}</option>`;
						}

						$('#addrid').html(option);
						$('#addrid').selectpicker('refresh');
					},
				});
			}

			controller.api.bindevent();
		},
		edit() {
			$('#table').bootstrapTable({
				columns: addAndEditTableColumns,
			});

			var BackProductList = Config.back.BackProductList;

			let tr = '';

			for (let item of BackProductList) {
				tr += getTr(item);
			}

			$('#table tbody').empty();

			$('#table tbody').html(tr);

			let timer;
			$('#c-ordercode').on('change', function () {
				const code = $(this).val();
				if (timer) clearTimeout(timer);
				timer = setTimeout(() => getInfo(code), 300);
			});

			function getInfo(code) {
				if (!code) return;
				$.ajax({
					type: 'post',
					url: 'depot/back/orderinfo',
					data: {
						code,
					},
					dataType: 'json',
					success: function (res) {
						if (res.code === 0) {
							Toastr.error(res.msg);

							return false;
						}

						$('#table').show();

						$('#table tbody').empty();

						let tr = '';

						for (let i = 0; i < res.data.productList.length; i++) {
							tr += getTr(res.data.productList[i]);
						}

						$('#table tbody').html(tr);

						// 收货地址
						let option = '';

						for (let item of res.data.addressList) {
							option += `<option value="${item.id}" ${
								item.id == res.data.businessaddrid ? 'selected="selected"' : ''
							}>联系人：${item.consignee} 联系方式：${item.mobile} 地址：${item.region_text} ${
								item.address
							}</option>`;
						}

						$('select.selectpicker[name="row[addrid]"]').empty();
						$('select.selectpicker[name="row[addrid]"]').html(option);
						$('select.selectpicker[name="row[addrid]"]').selectpicker('refresh');

						$('textarea[name="row[remark]"]').val('')
					},
				});
			}
			controller.api.bindevent();
		},
		fail() {
			controller.api.bindevent();
		},
		api: {
			// JS模块化的全局方法
			bindevent: function () {
				Form.api.bindevent($('form[role=form]'));
			},
		},
	};
	return controller;
});
